<template>
	<view class="cart" v-if="!loading">
		<page-box-empty v-if="(cartInfo.length == 0)" title="您还没有挑选任何商品" sub-title="可以去看看有那些想买的～" :show-btn="true" />
		<view v-else class="cart-container">
			<view class="order" v-for="(list, i) in cartInfo" :key="list.shop.id">
				<view class="order-cate">
					<view class="select" @click="toggleCateCheck(list, i)" v-if="list.items.filter(itm=>itm.sku.stock > 0).length > 0">
						<image v-show="list.items.filter((itm)=> !itm.selected && itm.sku.stock > 0).length !== 0 " class="check-icon" src="../../static/images/check.svg" mode=""></image>
						<image v-show="list.items.filter((itm)=> !itm.selected && itm.sku.stock > 0).length === 0 " class="check-icon" src="../../static/images/checked.svg" mode=""></image>
					</view>
					<view v-else class="select">
						<image class="check-icon" src="../../static/images/check-disabled.svg" mode=""></image>
					</view>
					<view class="order-title">
						{{list.shop.name}}
					</view>
				</view>
				<uni-swipe-action class="cart-swipe">
					<view class="item-box" v-for="(item, index) in list.items" :key="item.sku.id">
						<uni-swipe-action-item show="none" :index="item.id" :right-options="options" @click="deleterecord(item,index,i)">
							<view class="item" @click="toDetail(item)">
								<view class="select" @click.stop="toggleCheck(item, index, i)">
									<image v-show="item.sku.stock <= 0" class="check-icon" src="../../static/images/check-disabled.svg" mode=""></image>
									<image v-show="!item.selected && item.sku.stock > 0" class="check-icon" src="../../static/images/check.svg" mode=""></image>
									<image v-show="item.selected && item.sku.stock > 0" class="check-icon" src="../../static/images/checked.svg" mode=""></image>
								</view>
								<view class="pic">
									<image :src="item.sku.thumbnail ? item.sku.thumbnail : item.thumbnail" mode="aspectFill"></image>
								</view>
								<view class="content">
									<view class="good-name block">{{item.title}}</view>
									<view class="good-sku-name block">{{item.sku.title}}</view>
									<view class="good-return">可免单¥{{isLeader ? (item.sku.share_price * item.back_self_ratio / 100 /100 ).toFixed(2) : (item.sku.sale_price * item.back_self_ratio / 100 /100 ).toFixed(2)}}</view>
									<view class="good-foot">
										<view class="good-price">
											<template v-if="isLeader">
												¥{{(item.sku.share_price / 100).toFixed(2)}}
											</template>
											<template v-else>
												¥{{(item.sku.sale_price / 100).toFixed(2)}}
											</template>
										</view>
										<view v-if="item.sku.stock > 0 " @click.stop="() => {}">
											<number-box v-model="item.count" :name="item.sku.id" :cursor-spacing="60" :min="1" :max="item.sku.stock" @change="(v) => numberChange(v, index, i)"></number-box>
										</view>
										<text v-else class="good-foot-tip">库存不足</text>
									</view>
								</view>
							</view>
						</uni-swipe-action-item>
					</view>
				</uni-swipe-action>
			</view>
			<view class="total">
				<view class="total-count">
					<goods-price :price="total.price" txt="合计："></goods-price>
					<view v-if="total.discount > 0" class="total-discount">已优惠：￥{{(total.discount / 100).toFixed(2)}}</view>
				</view>
				<view class="total-btn" @click="submit">去结算（{{total.count}}）</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { goodCarts, shoppingCartActivitySku } from '@/http/apis.js';
	import { ref, computed } from 'vue';
	import { onShow } from '@dcloudio/uni-app';
	import { useMutations } from '../../store/hooks/useMutations';
	import { useGetters } from '../../store/hooks/useGetters';

	const { isLeader, carts, configs } = useGetters(['isLeader', 'carts','configs']);
	const { setCartBadge, setCarts } = useMutations(['setCartBadge', 'setCarts']);
	const cartInfo = ref([]);
	const options = ref([
		{
			text: '删除',
			style: {
				backgroundColor: '#dd524d'
			}
		}
	]);
	const loading = ref(false);
	const max_qty = ref(0);
	const skus = ref([]);
			
	onShow(() => {
		if (carts.value.length > 0) {
			let ids = [];
			carts.value.map(item => {
				ids.push(item.id)
			})
			let newIds = (Array.from(new Set(ids)));
			shippingCartActivity(newIds.join(','))
			
			uni.setTabBarBadge({
				index: 2,
				text: String(carts.value.length)
			})
		} else {
			cartInfo.value = [];
			uni.removeTabBarBadge({
				index: 1
			})
		}

		// 商品数量限制
		configs.value.map(item => {
			if (item.config_key == 'order_goods_max_qty') {
				max_qty.value = parseInt(item.config_value);
			}
		})
		setCartBadge();
	});
	
	const total = computed(() => {
		let total = {price: 0, count: 0, discount: 0};
		cartInfo.value.map(list => {
			list.items.map(item => {
				if (item.selected) {
					let price = isLeader.value ? item.sku.share_price : item.sku.sale_price;
					if (item.asku) {
						const activity_price = item.asku.activity_price;
						// activity_can_qty：活动商品可购买数量, 每人限购数量-已购数量，活动库存最小值,
						let activity_can_qty = Math.min(item.asku.limit_qty - item.asku.user_used_qty, item.asku.limit_total - item.asku.used_qty);
						if (activity_can_qty < item.count) {
							total.price += Number(activity_price * activity_can_qty);
							total.price += Number(price * (item.count - activity_can_qty));
							total.discount += (price - activity_price) * activity_can_qty;
						} else {
							total.price += Number(activity_price * item.count);
							total.discount += (price - activity_price) * item.count;
						}
					} else {
						total.price += Number(price * item.count);
					}
					total.count += Number(item.count);
				}
			})
		})
		return total;
	})
	const shippingCartActivity = (ids) => {
		shoppingCartActivitySku({goods_ids: ids}).then(res => {
			let skus = [];
			for (var i in res) {
				if (res[i]) {
					skus = skus.concat(res[i])
				} 
			}
			skus.value = skus;
			_shippingCarInfo(ids)
		})
	}
	const _shippingCarInfo = (ids) => {
		loading.value = true;
		uni.showLoading()
		goodCarts({goods_ids: ids}).then(res => {
			loading.value = false;
			uni.hideLoading();
			let cartInfo = [];
			
			carts.value.map(cart => {
				res.map(item => {
					let skuIndex = item.goods.goods_sku.findIndex(sku => sku.id == cart.skuId);
					let asku = skus.value.find(item => item.sku_id === cart.skuId && (item.limit_total > item.used_qty && item.user_used_qty < item.limit_qty))
					if (item.goods.id == cart.id) {
						cart.sku = skuIndex > -1 ? item.goods.goods_sku[skuIndex] : item.goods.goods_sku[0];
						cart.asku = asku ? asku : null;
						cart.shop = item.shop;
						cart.back_self_ratio = item.back_self_ratio;
						cart.title = item.goods.title;
						cart.thumbnail = item.goods.thumbnail;
					}
				})
			})
			carts.value.map(item => {
				let cartIndex = cartInfo.findIndex(cart => cart.shop.id == item.shop.id);
				let stock = item.sku.stock;
				if (max_qty.value > 0) {
					stock = Math.min(item.sku.stock, max_qty.value)
				}
				
				if (item.sku.status !== 1 || item.shop.status !== 2) {
					stock = 0
				}
				if (stock <= 0) item.selected = false;
				item.count = Math.max(item.count, 1)
				
				if (cartIndex > -1) {
					cartInfo[cartIndex].items.push({
						count: Math.min(item.count, stock),
						back_self_ratio: item.back_self_ratio,
						selected: item.selected,
						sku: {...item.sku, stock: stock},
						asku: item.asku,
						id: item.id,
						title: item.title,
						thumbnail: item.thumbnail
					});
				} else {
					let cartItem = {
						shop: item.shop,
						selected: false,
						items: [{
							count: Math.min(item.count, stock),
							back_self_ratio: item.back_self_ratio,
							selected: item.selected,
							sku: {...item.sku, stock: stock},
							asku: item.asku,
							id: item.id,
							title: item.title,
							thumbnail: item.thumbnail
						}],
					}
					cartInfo.push(cartItem)
				}
			})
			cartInfo.value = cartInfo;
			updateCartStore()
		}).catch(res => {
			console.log(res);
			updateCartStore()
			loading.value = false;
			uni.hideLoading();
		})
	}
	// 不同商家下的全选/全取消
	const toggleCateCheck = (list, i) => {
		cartInfo.value[i].selected = list.items.filter((itm)=> !itm.selected && itm.sku.stock > 0).length > 0;
		list.items.map(item => {
			if (item.sku.stock > 0) {
				item.selected = cartInfo.value[i].selected;
			} else {
				item.selected = false;
			}
		})
		updateCartStore();
	}
	// 单个商品的选择与取消 index 子索引 i 父索引
	const toggleCheck = (item, index, i) => {
		if (item.sku.stock <= 0) {
			cartInfo.value[i].items[index].selected = false
		} else {
			cartInfo.value[i].items[index].selected = !item.selected;
		}
		let flagNum = 0; // 0代表全部不选，等于数组长度表示全选
		cartInfo.value[i].items.map(item => {
			if (item.selected) flagNum ++
		})
		if (flagNum == cartInfo.value[i].items.length) cartInfo.value[i].selected = true;
		else cartInfo.value[i].selected = false;
		updateCartStore();
	}
	// 单个商品的删除 index 子索引 i 父索引
	const deleterecord = async (item, index, i) => {
		cartInfo.value[i].items.splice(index, 1);
		if (cartInfo.value[i].items.length == 0) {
			cartInfo.value.splice(i, 1);
		}
		uni.showToast({
			title: '删除成功',
		});
		updateCartStore();
	}
	// 商品改变数量 index 子索引 i 父索引
	const numberChange = async (value, index, i) => {
		cartInfo.value[i].items[index].count = value
		updateCartStore();
	}
	// 更改商品数量和删除时，重新缓存carts数据
	const updateCartStore = () => {
		let carts = [];
		cartInfo.value.forEach(list => {
			list.items.forEach(item => {
				carts.push({id: item.id, count: item.count,skuId: item.sku.id, selected: item.selected})
			})
		});
		console.log('update----', carts)
		setCarts(carts);
		setCartBadge();
	}
	// 去结算
	const submit = () => {
		if (total.value.count < 1) {
			uni.showToast({
				icon: 'none',
				title: '请选择商品'
			})
		} else {
			let ids = []
			let qty = []
			let skuId = []
			carts.value.forEach((c) => {
				if (c.selected) {
					ids.push(c.id)
					qty.push(c.count)
					skuId.push(c.skuId)
				}
			})
			uni.navigateTo({
				url: `../pay/index?clear_cart=1&id=${ids.join(",")}&qty=${qty.join(",")}&skuId=${skuId.join(",")}`
			})
		}
	}
	const toDetail = (item) => {
		uni.navigateTo({
			url: `/pages/goodsDetail/index?id=${item.id}`
		})
	}
</script>
<style scoped lang="scss">
	.cart {
		width: 100%;
		min-height: 100vh;
		padding: 25rpx 25rpx 0 25rpx;
		box-sizing: border-box;
		background-color: #F8FAFD;
	}
	.cart-container {
		width: 100%;
		padding-bottom: 100rpx;
		box-sizing: border-box;
	}
	.order {
		width: 100%;
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 32rpx 22rpx;
		box-sizing: border-box;
		margin-bottom: 24rpx;
		.select {
			width: 58rpx;
			height: 100%;
			display: flex;
			align-items: center;
			.check-icon {
				width: 40rpx;
				height: 40rpx;
			}
		}
		.order-cate {
			display: flex;
			align-items: center;
			.order-title {
				color: #2E2E2E;
				font-size: 28rpx;
				line-height: 44rpx;
				margin-left: 24rpx;
			}
		}
		.uni-swipe {
			width: 100%;
			height: 180rpx;
			margin-bottom: 32rpx;
		}
		.item-box {
			height: 180rpx;
			margin-top: 32rpx;
		}
		.item {
			display: flex;
			width: 100%;
			height: 180rpx;
			.pic {
				margin-right: 20rpx;
				image {
					width: 225rpx;
					height: 180rpx;
					border-radius: 16rpx;
				}
			}
			.content {
				flex: 1;
				overflow: auto;
				.good-name {
					height: 40rpx;
					color: #000;
					font-size: 24rpx;
					line-height: 40rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
				.good-sku-name {
					height: 40rpx;
					color: #969799;
					font-size: 24rpx;
					line-height: 40rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}

				.good-return {
					padding: 0 8rpx;
					box-sizing: border-box;
					background: rgba(252, 73, 81, 0.1);
					font-size: 24rpx;
					font-weight: normal;
					line-height: 36rpx;
					height: 36rpx;
					color: #FC4951;
					border-radius: 4rpx;
					margin-top: 4rpx;
					display: inline-block;
				}
				 .good-foot {
					 display: flex;
					 justify-content: space-between;
					 align-items: flex-end;
					 margin-top: 6rpx;
					 &-tip{
						 color: #999;
						 font-size: 26rpx;
					 }
					 .good-price {
						 color: #FC4951;
						 font-weight: bold;
						 font-weight: 24rpx;
					 }
				 }

				.delivery-time {
					color: #e5d001;
					font-size: 24rpx;
				}
			}
		}

		.bottom {
			display: flex;
			margin-top: 40rpx;
			padding: 0 10rpx;
			justify-content: space-between;
			align-items: center;

			.btn {
				line-height: 52rpx;
				width: 160rpx;
				border-radius: 26rpx;
				border: 2rpx solid #f00;
				font-size: 26rpx;
				text-align: center;
				color: #f00;
			}

			.evaluate {
				color: #f00;
				border-color: #f00;
			}
		}
	}
	.total {
		position: fixed;
		z-index: 99;
		left: 0;
		bottom: 0rpx;
		width: 100%;
		height: 98rpx;
		background-color: #fff;
		padding-right: 25rpx;
		box-sizing: border-box;
		display: flex;
		justify-content: flex-end;
		align-items: center;
		.total-price {
			color: #2E2E2E;
			font-size: 24rpx;
			.amount {
				color: #FC4951;
				font-size: 28rpx;
			}
		}
		.total-count {
			display: flex;
			flex-direction: column;
			justify-content: center;
			.total-discount {
				color: #969799;
				font-size: 24rpx;
				line-height: 32rpx;
			}
		}
		.total-btn {
			height: 72rpx;
			line-height: 40rpx;
			padding: 16rpx 24rpx;
			box-sizing: border-box;
			border-radius: 36rpx;
			background: linear-gradient(113deg, #FADF5D 18%, #F7D35D 81%);
			text-align: center;
			color: #30240A;
			font-size: 28rpx;
			margin-left: 25rpx;
		}
	}
	.divider {
		width: 240rpx;
		height: 40rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		position: relative;
		margin: 40rpx auto;
		&::after {
			content: '';
			width: 138rpx;
			height: 1rpx;
			background-color: #EBEDF0;
			position: absolute;
			top: 19rpx;
			left: -150rpx;
		}
		&::before {
			content: '';
			width: 138rpx;
			height: 1rpx;
			background-color: #EBEDF0;
			position: absolute;
			top: 19rpx;
			right: -150rpx;
		}
		.icon {
			width: 40rpx;
			height: 40rpx;
		}
		.txt {
			color: #2E2E2E;
			font-size: 32rpx;
			line-height: 40rpx;
		}
	}
	.goods-container {
		width: 100%;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		margin-top: 24rpx;
		padding-bottom: 20rpx;
		.good-list {
			width: 340rpx;
			height: 460rpx;
			margin-bottom: 24rpx;
		}
	}
	
</style>
